package org.whb.basic.Controller;


import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.whb.basic.util.AjaxResult;
import org.whb.basic.util.FastDfsUtil;

import java.io.File;

@RestController
@RequestMapping("/fastDfs")
public class FastDfsController {

    @PostMapping("/upload")
    public AjaxResult uploadFile(@RequestParam(required = true,value = "file")MultipartFile file){
        try {
            String filename = file.getOriginalFilename();
            String extName = filename.substring(filename.lastIndexOf(".")+1);
            String filePath = FastDfsUtil.upload(file.getBytes(), extName);
            //将上传文件地址返回给前端
            return new AjaxResult().setResultObj(filePath);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("服务器繁忙，请稍后再试！！！");
        }
    }

    @DeleteMapping
    public AjaxResult removeFile(@RequestParam(required = true,value = "path") String path){
        try {
            String pathTmp = path.substring(1); // goup1/xxxxx/yyyy
            String groupName =  pathTmp.substring(0, pathTmp.indexOf("/")); //goup1
            String remotePath = pathTmp.substring(pathTmp.indexOf("/")+1);// /xxxxx/yyyy
            FastDfsUtil.delete(groupName, remotePath);
            return new AjaxResult();
        } catch (Exception e){
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("服务器出错啦，请稍后再访问！！！");
        }
    }

}
